package www.wen.com.common.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import www.wen.com.common.data.key.KEY_AUTO_THEME
import www.wen.com.common.data.key.KEY_DEFAULT_THEME
import www.wen.com.common.ext.toCoverTheme
import www.wen.com.common.theme.ThemeControl.LocalIsAutoTheme
import www.wen.com.common.theme.ThemeControl.LocalPallet
import www.wen.com.common.util.SpUtil


private val LocalCustomThemes = staticCompositionLocalOf<ThemeData> {
    error("No JetsnackColorPalette provided")
}

private val DarkThemeData = ThemeData(
    textColor1 = Purple80,
)

private val LightThemeData = ThemeData(
    textColor1 = Purple40,
)

private val BlueThemeData = ThemeData(
    textColor1 = Purple40,
)

@Composable
fun AppTheme(
    isAutoTheme: Boolean = LocalIsAutoTheme.current,
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val themeData = if(isAutoTheme){
        if(darkTheme){
            DarkThemeData
        }else{
            LightThemeData
        }
    }else{
        when(getCurrentTheme()){
            Theme.DARK -> DarkThemeData
            Theme.LIGHT -> LightThemeData
            Theme.BLUE -> BlueThemeData
        }
    }
    CompositionLocalProvider(
        LocalCustomThemes provides themeData
    ) {
        MaterialTheme(
            colorScheme = colorScheme.copy(),
            typography = Typography,
            content = content
        )
    }
}


data class ThemeData(
    val textColor1: Color
)

enum class Theme {

    DARK, LIGHT, BLUE;

}



object ThemeControl {

    /** 使用一个变量维护当前主题 */
    val LocalPallet = staticCompositionLocalOf{
        getDefaultTheme()
    }


    /** 根据系统自动变更 */
    val LocalIsAutoTheme = staticCompositionLocalOf{
        getIsAutoTheme()
    }

    /** 根据系统自动变更 */
    val LocalColors = staticCompositionLocalOf{
        mutableListOf(Color.Black,Color.White,Color.Blue)
    }

}

/**
 * 获取默认主题
 */
fun getDefaultTheme() = SpUtil.decodeInt(KEY_DEFAULT_THEME, Theme.LIGHT.ordinal).toCoverTheme()

/**
 * 获取默认主题
 */
@Composable
fun getCurrentTheme() = if (getIsAutoTheme()) {
    SpUtil.decodeInt(KEY_DEFAULT_THEME, Theme.LIGHT.ordinal).toCoverTheme()
} else {
    LocalPallet.current
}

/**
 * 是否根据系统自动变更
 */
fun getIsAutoTheme() = SpUtil.decodeBoolean(KEY_AUTO_THEME, true)

